package com.dongrj.framework.web.condition;

import com.dongrj.framework.core.utils.CollectionUtils;
import com.dongrj.framework.core.utils.ObjectUtils;
import com.dongrj.framework.core.utils.StringUtils;
import org.springframework.boot.autoconfigure.condition.ConditionOutcome;
import org.springframework.boot.autoconfigure.condition.SpringBootCondition;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.core.env.Environment;
import org.springframework.core.type.AnnotatedTypeMetadata;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;
/**
 * @author dongrongjun
 * @date 2020/4/2
 */
public class EnvironmentCondition extends SpringBootCondition {
    @Override
    public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) {
        Map<String, Object> annotationAttributes = metadata.getAnnotationAttributes(ConditionalEnv.class.getName());
        Object value = annotationAttributes.get("value");
        String[] envs = ObjectUtils.cast(value, String[].class);
        if (Objects.isNull(envs)) {
            return new ConditionOutcome(false, "error");
        }
        List<String> envList = Arrays.stream(envs).collect(Collectors.toList());
        String active = getEnv(context.getEnvironment());
        if (StringUtils.isEmpty(active)) {
            return new ConditionOutcome(false, "error");
        }
        String[] split = active.split(",");
        List<String> strings = Arrays.asList(split);
        if (CollectionUtils.hasIntersection(envList, strings)) {
            return new ConditionOutcome(true, "ok");
        }
        return new ConditionOutcome(false, "error");
    }

    private static String getEnv(Environment environment) {
        return environment.getProperty("spring.profiles.active");
    }

}
